package com.jzg.mvc.api.room;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Path;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jzg.common.controller.BaseController;
import com.jzg.common.model.biz.Room;
import com.jzg.common.model.biz.RoomLog;
import com.jzg.common.util.UuidUtil;

@Path(value = "/api/room", viewPath = "")
public class RoomController extends BaseController{
	
	protected final Log LOG = Log.getLog(getClass());
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String userId = get("userId");
		String keyword = getPara("keyword");
		
		String sqlExceptSelect = " from " + Room.TABLE_NAME + " o  where 1=1 ";
		
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " and ( o.name like '%"+keyword+"%' or o.code like '%" + keyword + "%' ) ";
		}
		if(!StrKit.isBlank(userId)) {
			//sqlExceptSelect += " and o.userId = '"+userId+"' ";
		}
		
		sqlExceptSelect += "  order by  o.code ";
		Page<Room> page = Room.dao.paginate(pageNumber, pageSize, "select o.*, '"+DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss")+"' as currentTime, "
				+ " (select inquirer from biz_room_log where roomId=o.id and createTime=o.updateTime) as inquirer, "
				+ " (SELECT NAME FROM SYS_ORG WHERE ID IN ( select orgId from biz_room_log where roomId=o.id and createTime=o.updateTime ) ) orgName ", sqlExceptSelect);
		System.out.println(JsonKit.toJson(page.getList()));
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	public void save () {
		Room room = getModel(Room.class);
		if(room==null) {
			renderError("参数不完整！");
			return;
		}
		if (StrKit.notBlank(room.getId())) {
			if (room.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			room.setId(UuidUtil.getUUID());
			room.setCreateTime(new Date(System.currentTimeMillis()));
			room.setUpdateTime(new Date(System.currentTimeMillis()));
			room.setStatus("0");
			if (room.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	/***
	 * 删除
	 * @throws Exception
	 */
	public void delete() throws Exception {
		String id = getPara("id");
		Room room = Room.dao.findById(id);
		if (room != null) {
			if (room.delete()) {
				renderSuccess("删除成功！");
				Db.delete("delete from "+RoomLog.TABLE_NAME+" where roomId=?",room.getId());
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	/***
	 * 启用或停用
	 * @throws Exception
	 */
	public void updateStatus() throws Exception {
		String id = getPara("id");
		String status = getPara("status");
		String inquirer = getPara("inquirer");
		String orgId = getPara("orgId");
		
		if(StrKit.isBlank(status)) {
			renderError("参数不完整！");
			return;
		}
		
		if(StrKit.equals("1", status)) {
			if(StrKit.isBlank(inquirer)) {
				renderError("参数不完整！");
				return;
			}
		}
		
		Room room = Room.dao.findById(id);
		if (room != null) {
			
			if(StrKit.equals(status, room.getStatus())) {
				renderError("房间正在该状态下！");
				return;
			}
			
			room.setStatus(status);
			Date time = new Date(System.currentTimeMillis());
			room.setUpdateTime(time);
			if (room.update()) {
				if(StrKit.equals("1", status) || StrKit.equals("2", status)) {
					List<RoomLog> logs = RoomLog.dao.find("select * from "+RoomLog.TABLE_NAME+" where status='0' and roomId=? ",room.getId());
					for (RoomLog roomLog : logs) {
						roomLog.setStatus("1");
						roomLog.setEndTime(time);
						roomLog.update();
					}
					RoomLog log = new RoomLog();
					log.setId(UuidUtil.getUUID());
					log.setRoomId(room.getId());
					log.setCreateTime(time);
					log.setStatus("0");
					log.setInquirer(inquirer);
					log.setOrgId(orgId);
					log.save();
				} else {
					RoomLog roomLog = RoomLog.dao.findFirst("select * from "+RoomLog.TABLE_NAME+" where status='0' and roomId=? ",room.getId());
					if(roomLog!=null) {
						roomLog.setStatus("1");
						roomLog.setEndTime(time);
						roomLog.update();
					}
				}
				renderSuccess("操作成功！");
			} else {
				renderError("操作失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	/***
	 * 统计
	 * @throws Exception
	 */
	public void getChart() throws Exception {
		String userId = getPara("userId");
		String sql = " select `status`,COUNT(id) count from biz_room where 1=1 ";
		
		if(!StrKit.isBlank(userId)) {
			//sql += " and userId = '"+userId+"' ";
		}
		sql += " GROUP BY status ";
		List<Record> lists = Db.find(sql);
		
		Map<String, Integer> returnMap = new HashMap<String, Integer>();
		returnMap.put("use", 0);
		returnMap.put("free", 0);
		returnMap.put("yuyue", 0);
		returnMap.put("total", 0);
		if(lists!=null && lists.size()>0) {
			int use=0;int free=0;int yuyue=0;
			for (Record record : lists) {
				if(StrKit.equals("1", record.getStr("status"))) {
					use = record.getInt("count");
					returnMap.put("use", use);
				}else if(StrKit.equals("2", record.getStr("status"))){
					yuyue = record.getInt("count");
					returnMap.put("yuyue", yuyue);
				}else {
					free = record.getInt("count");
					returnMap.put("free", free);
				}
			}
			returnMap.put("total", use + free + yuyue);
		}
		renderSuccess("查询成功！", returnMap);
	}
	
	public void listLogData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String id = getPara("id");
		String status = getPara("status");
		String keyword = getPara("keyword");
		
		String sqlExceptSelect = " from " + RoomLog.TABLE_NAME + " o,"+Room.TABLE_NAME+" r where o.roomId=r.id ";
		
		if (!StrKit.isBlank(id)) {
			sqlExceptSelect += " and  o.roomId='"+id+"' ";
		}
		if (!StrKit.isBlank(status)) {
			sqlExceptSelect += " and  o.status='"+status+"' ";
		}
		if(!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " and o.inquirer like '%"+keyword+"%' ";
		}
		sqlExceptSelect += "  order by o.createTime desc ";
		Page<RoomLog> page = RoomLog.dao.paginate(pageNumber, pageSize, "select o.*, "
				+ " r.name,r.code,CASE o.`status` WHEN 1 THEN '已结束' ELSE '使用中' END as statusName ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
}
